import time

import requests
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

import setting
from app.service.DataDeal import DataDeal
from common.handler.logHandler import LogHandler
from common.exception.ReturnException import ReturnException

log = LogHandler(setting.LOG_NAME)


# 打码
class VifyCode:
    def __init__(self):
        # self.平台token = 'Bearer ' + data['接码key']

        打码key = DataDeal().读打码key()
        self.平台token = 打码key
        self.websiteKey = '6LdBmqYZAAAAALTuNWDI9WSTVFkyAkyCNvc72Ebm'
        self.pageurl = 'https://jp.match.com/'
        # self.pageurl = "https://gametrade.jp/exhibits/new"
        self.taskId = ''

    def create_task(self):
        log.debug('创建打码任务')
        url = 'https://api.ez-captcha.com/createTask'
        times = 3
        while times > 0:
            times -= 1
            try:

                headers = {
                    'Content-Type': 'application/json'}
                data1 = {
                    "clientKey": "e1a7f6b509544a759646b9139e6524c2849319",
                    "appId": "33417",
                    "task":
                        {
                            "type": "ReCaptchaV2TaskProxyless",
                            "websiteURL": self.pageurl,
                            "websiteKey": self.websiteKey,
                            "isInvisible": True,
                        },

                }

                response = requests.post(url, headers=headers, json=data1
                                         , timeout=60000,
                                         verify=False
                                         )
                if response.ok:
                    res = response.json()
                    if res and res.get('errorCode'):
                        raise ReturnException.return_and_log('打码平台无法使用:%s' % res)
                    self.taskId = res['taskId']
                    log.debug('返回的任务标识:%s' % self.taskId)
                    return True
                else:
                    log.error('提交任务失败:%s' % response)
                    log.debug('提交任务失败,等待5秒后重新提交')
                    time.sleep(5)
            except ReturnException as e:
                raise e
            except Exception as e:
                log.error('打码平台创建任务错误捕获>>%s' % e)
                time.sleep(2)

    def query_result(self):
        log.debug('查询结果')
        headers = {
            'Content-Type': 'application/json'
        }

        data2 = {
            "clientKey": self.平台token,
            "taskId": self.taskId
        }

        try_times = 0
        while 1:
            response = requests.post('https://api.ez-captcha.com/getTaskResult',
                                     headers=headers, json=data2, proxies=self.proxies, verify=False)
            if response.ok:
                if response.json()['status'] == 'ready':
                    log.debug('打码结果查询成功')
                    result = response.json()['solution']['gRecaptchaResponse']
                    log.debug('result:%s' % result)
                    return result

                elif response.json()['status'] == "processing":
                    log.debug('打码中请稍等...')
                    if try_times >= 19:
                        log.debug('查询等待过久,重新打码')
                        return False

                    time.sleep(5)
                    try_times += 1

            else:
                log.debug('查询失败请查看:%s' % response.text)
                time.sleep(5)

                return False

    def get_code(self):
        log.debug('验证执行')
        self.create_task()
        return self.query_result()
